import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus_seven/apis/user.dart';
import 'package:flutter_enjoy_plus_seven/utils/Emitter.dart';
import 'package:flutter_enjoy_plus_seven/utils/toast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key, required this.userInfo});
  // 用户信息
  final Map<String, dynamic> userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 昵称输入框控制器
  final _nickNameController = TextEditingController();

  // 头像
  String _avatar = '';

  @override
  void initState() {
    super.initState();
    // 昵称输入框内容赋值
    _nickNameController.text = widget.userInfo['nickName'];
    // 用户没点保存按钮，子组件的头像 跟 父组件的头像 是独立的
    _avatar = widget.userInfo['avatar'] ?? '';
  }

  // 保存用户信息
  _saveUserInfo() async {
    // 1. 获取昵称
    final nickName = _nickNameController.text;
    // 1.1 判断昵称是否为空
    if (nickName.isEmpty) {
      PromptAction.showError("昵称不能为空");
      return;
    }
    // 1.2 正则合法性校验
    RegExp reg = RegExp(r'^[\u4e00-\u9fa5a-zA-Z0-9_]{2,18}$');
    if (!reg.hasMatch(nickName)) {
      PromptAction.showError("昵称只能包含中文、字母、数字和下划线，长度2-18字符");
      return;
    }
    // 2.1 调用更新用户信息接口
    await UserApi.updateUserInfo(nickName);
    // 2.2 上传用户头像
    await _uploadAvatar();
    // 3. 提示保存成功
    PromptAction.showSuccess('保存成功');
    // 5. 更新用户信息
    eventBus.fire(GetUserInfoEvent());
    // 4. 关闭当前页面
    if (mounted) {
      Navigator.pop(context);
    }
  }

  // 上传头像
  _uploadAvatar() async {
    // 如果头像字段是网络地址，说明用户没有更换头像，无需上传
    if (widget.userInfo["avatar"].toString().startsWith("http")) {
      return;
    }
    // 需构建成二进制文件对象
    final file = kIsWeb
        ? MultipartFile.fromBytes(
            await XFile(widget.userInfo["avatar"]).readAsBytes(), // 读取图片为字节数组
            filename: 'avatar.png', // 指定上传文件名
            contentType: DioMediaType("image", 'png'), // 指定文件类型为 image/png
          )
        : MultipartFile.fromFileSync(widget.userInfo["avatar"]); // 鸿蒙、安卓、IOS 兼容
    // 按后端接口字段要求，构造 FormData 数据
    final formData = FormData.fromMap({
      "file": file,
      "type": 'avatar',
    });
    // 调用用户API上传头像
    await UserApi.uploadPhoto(formData);
    // 打印上传结果，实际开发可根据需要处理返回值
    eventBus.fire(GetUserInfoEvent());
  }

  // 上传头像
  _pickPhoto(ImageSource source) async {
    try {
      // 创建图片选择器
      final ImagePicker picker = ImagePicker();
      // 从相册获取
      final XFile? image = await picker.pickImage(source: source);
      PromptAction.showSuccess(image?.path ?? '');
      if (image != null) {
        print(image.path); // blob 图片路径，浏览器临时路径(相当于鸿蒙的沙箱路径)
        setState(() {
          // 预览头像
          _avatar = image.path;
          // 关闭弹层
          Navigator.pop(context);
        });
      }
    } catch (e) {
      PromptAction.showError(e.toString());
    }
  }

  // 显示选择头像弹层
  void _showAvatarDialog() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SizedBox(
          width: double.infinity,
          height: 180,
          child: Column(
            children: [
              Container(
                alignment: Alignment.center,
                height: 60,
                decoration: const BoxDecoration(
                    border: Border(
                        bottom: BorderSide(width: 0.5, color: Colors.grey))),
                child: GestureDetector(
                  onTap: () {
                    _pickPhoto(ImageSource.camera); // 拍照，必须用实体机
                  },
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.camera_alt),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "拍照",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
              ),
              Container(
                alignment: Alignment.center,
                height: 60,
                decoration: const BoxDecoration(
                    border: Border(
                        bottom: BorderSide(width: 0.5, color: Colors.grey))),
                child: GestureDetector(
                  onTap: () {
                    _pickPhoto(ImageSource.gallery);
                  },
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.photo_album),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "相册",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
              ),
              Container(
                alignment: Alignment.center,
                height: 60,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.cancel_outlined),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "取消",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  _getAvatarImage() {
    if (_avatar.isEmpty) {
      return Image.asset(
        'assets/images/avatar_1.jpg',
        width: 30,
        height: 30,
      );
    } else if (kIsWeb || _avatar.toString().startsWith("http")) {
      // kIsWeb 为 true 表示当前是 Web 端
      // 判断是否为 Web 端，blob 图片路径，直接通过 Image.network 渲染
      // 如果头像字段是网络地址，也直接通过 Image.network 渲染
      return Image.network(
        _avatar,
        width: 30,
        height: 30,
      );
    } else {
      // 其他平台，Android、iOS、ohos 平台，通过 Image.file 渲染
      return Image.file(
        File(_avatar),
        width: 30,
        height: 30,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () {
                    _showAvatarDialog();
                  },
                  child: Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: _getAvatarImage(),
                      ),
                      const Icon(Icons.arrow_forward_ios, size: 12)
                    ],
                  ),
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _saveUserInfo();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
